<template>
  <div v-loading="isLoading">
    <el-upload :before-upload="handleBeforeUpload" :show-file-list="false" class="upload-demo" drag
      :http-request="handleUpload" :multiple="props.multiple">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖动文件到此或 <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          支持附件类型{{ props.exNames ? props.exNames.join(',') : sysConfig.getFileExnames }}，
          附件大小{{ props.maxSize ? (props.maxSize / 1024 / 1024).toFixed(2) : (sysConfig.getFileSize / 1024 /
            1024).toFixed(2) }}mb {{ props.multiple ? '多选' : '单选' }}
        </div>
      </template>
    </el-upload>
  </div>
  <div v-for="state in uploadfiles" :key="state.index" style="max-width: 100%;overflow:auto;">
    <el-progress :percentage="state.pnum">
      <el-button text>{{ state.name }} -上传中...</el-button>
    </el-progress>
  </div>
</template>
<script setup lang="ts">
import Farm2Request from '@/service/remoteRequests/Farm2Request';
import { useSystemConfigStore } from '@/store/useSystemConfigStore';
import {  reactive, ref } from 'vue';
import type { DataResponse } from "@/types/commons/DataResponse";
import type { FileUploadState } from '../utils/fileUploadState';

const sysConfig = useSystemConfigStore();
const isLoading = ref(false);
const props = defineProps({
  successHandle: {
    type: Function,
    required: true
  },
  updatingHandle: {
    type: Function,
    required: false
  },
  errorHandle: {
    type: Function,
    required: true
  },
  exNames: {
    type: Array,
    required: false
  },
  maxSize: {
    type: Number,
    required: false
  },
  multiple: {
    type: Boolean,
    required: true
  },
});

const uploadfiles = reactive<FileUploadState[]>([]);



function handleBeforeUpload(file: File) {
  if (props.exNames) {

    const fileExtension = file.name.split('.').pop()?.toLowerCase();

    const isValidFile = fileExtension && props.exNames.includes(fileExtension);
    if (!isValidFile) {
      props.errorHandle({ message: '文件类型不允许上传:' + file.name });
      return false;
    }
  }
  if (props.maxSize) {
    if (file.size > props.maxSize) {
      props.errorHandle({ message: '文件超大:' + (file.size / 1024 / 1024).toFixed(2) });
      return false;
    }
  }
  return true;
}


function findByIndex(targetIndex: number, files: FileUploadState[]): FileUploadState | undefined {
  return files.find(item => item.index === targetIndex);
}

function removeByIndex(targetIndex: number, files: FileUploadState[]) {

  const indexInArray = files.findIndex(item => item.index === targetIndex);
  if (indexInArray !== -1) {

    files.splice(indexInArray, 1);
  }
}


const handleUpload = (option: { file: File }) => {
  const index = uploadfiles.length + 1;
  uploadfiles.push({
    name: option.file.name,
    index: index,
    pnum: 0,
  });
  if (props.updatingHandle) {

    props.updatingHandle();
  }
  Farm2Request.uploadFile("api/files/upload", isLoading, option.file, (pnum: number) => {
    if (pnum > 0) {
      if (findByIndex(index, uploadfiles)) {
        findByIndex(index, uploadfiles)!.pnum = pnum;
      }
    }
  }).then((response: DataResponse) => {

    removeByIndex(index, uploadfiles);

    props.successHandle(response);

  }).catch((msg: Error) => {
    if (findByIndex(index, uploadfiles)) {
      const state = findByIndex(index, uploadfiles)
      props.errorHandle({ message: state?.name + msg.message });
    }
    removeByIndex(index, uploadfiles);
  });
}

</script>
<style scoped>
/* 样式可以根据需要添加 */
</style>
